<?php
/**
* This is controller use for public area
* @author: hungnq@younetco.com
* @version: 0.1
*/


class Contest_ReportController extends YouNet_Controller_Action{

	/**
	 *
	 * @var Core_Model_Contest 
	 */
	private $_contest;
	
	public function preDispatch()
	{
		parent::preDispatch();
		$this->view->use_admin_menu = 1;
		$this->view->render('manage/select_fanpages.phtml');
		$idContest		= $this->_getContestId();
		$contestModel	= new Core_Model_DbTable_Contests();

		/* @var $contestRow Core_Model_Contest */
		$contestRow		= $contestModel->findOne($idContest);

		if(
			!empty($contestRow->id)
			&& $contestRow->hasAdminPermission($this->_id_user, $this->_social->getUserPageIds())
		)
		{
			$this->_contest = $contestRow;
		}
		else
		{
			throw new Exception('Bad request',404);
		}
	}
	
	private function _getContestId()
	{
		$idContest = $this->_getParam('id', 0);
		if( $idContest <= 0 )
		{
			throw new Exception('Bad request',404);
		}
		return $idContest;
	}
	public function chartDataAction(){
		$this->disableAutoRender();
		$id_pages   = Core_Model_DbTable_Pages::getInstance()->getArrayPagesID($this->_contest->id);
		
		$tlist = $this->_getParam('tlist', '');
		$dlist = $this->_getParam('dlist', '');

		$fromDate	= $this->_getParam('fromDate', '');
		$fromDate	= !empty($fromDate) ? strtotime($fromDate) : $this->_contest->getStartDate();
		$toDate	= $this->_getParam('toDate', '');
		$toDate		= !empty($toDate) ? strtotime($toDate) : $this->_contest->getEndDate();
		
		$date		= array(
			'fromDate'	=> $fromDate,
			'toDate'	=> $toDate
		);
		if (!empty($dlist))
		{
			list($rangeAgeGender, $dataAgeGender) = $this->getDataGenderAge($dlist, $date);
			echo json_encode(array(
				'range' => $rangeAgeGender,
				'data'	=> $dataAgeGender
			));
		}
		else if (!empty($tlist))
		{
			switch ($tlist) {
				case YouNet_Model_DbTable_Likes::STATISTIC_KEY:
					$data = YouNet_Model_DbTable_Likes::getLikeStatistic($this->_contest->id, $id_pages, $date);
					break;
				case Core_Model_DbTable_Votes::STATISTIC_KEY:
					$data = Core_Model_DbTable_Votes::getVoteStatistic($this->_contest->id, $date);
					break;
				case YouNet_Model_DbTable_Visitors::STATISTIC_KEY:
					$data = YouNet_Model_DbTable_Visitors::getVisitorViewStatistic($this->_contest->id, $id_pages, $date);
					break;
				default:
					break;
			}
			$dataPerformance[] = array_merge($data, array('showInLegend' => false));
			echo json_encode($dataPerformance);
		}
	}
	public function indexAction()
	{
		$id_pages   = Core_Model_DbTable_Pages::getInstance()->getArrayPagesID($this->_contest->id);
		$ageGenderList		= $this->_getParam('dlist', YouNet_Model_DbTable_Visitors::STATISTIC_KEY);
		
		if ($this->_contest->isFinishedTimeline())
		{
			$this->view->listPhase = Core_Model_DbTable_Phases::getInstance()->listPhasesByContest($this->_contest->id);
			$this->view->statisticData = Core_Model_DbTable_Contests::getInstance()->getStatisticData($this->_contest->id, $this->view->listPhase[0]['date_start'], $this->view->listPhase[count($this->view->listPhase)-1]['date_end']);

			$form = new Contest_Form_StatisticControl();
			$activityForm = new Contest_Form_StatisticActivityControl();
			$demographicForm = new Contest_Form_StatisticDemographicControl();
			$range = $dataTraffic = $dataPerformance = $rangeAgeGender = $dataAgeGender = array();
			if( isset($_POST['form_submitted']) )
			{
				if($form->isValid($_POST))
				{
					$list		= explode(',',$this->_getParam('tlist'));
					$params = $this->_getAllParams();
					$params['options'] = isset($params['tlist']) ? explode(",", $params['tlist']) : array(YouNet_Model_DbTable_Visitors::STATISTIC_KEY, YouNet_Model_DbTable_Likes::STATISTIC_KEY, Core_Model_DbTable_Votes::STATISTIC_KEY);

					$fromDate	= $this->_getParam('fromDate', '');
					if (!empty($fromDate))
						$fromDate	= strtotime($fromDate);
					else
					{
						$timeStart = $this->_contest->_getTimeStart();
						if ($timeStart > time())
							$fromDate = Core_Util::getTimeAt0($this->_contest->time_created);
						else
							$fromDate = Core_Util::getTimeAt0($this->_contest->_getTimeStart());
						$params['fromDate'] = Date("m/d/Y", $fromDate);
					}

					$toDate	= $this->_getParam('toDate', '');
					if (!empty($toDate))
						$toDate	= strtotime($toDate);
					else
					{
						$timeEnd = $this->_contest->_getTimeEnd();
						if ($timeEnd > time())
							$toDate = time();
						else
							$toDate = Core_Util::getTimeAt0($this->_contest->_getTimeEnd());
						$params['toDate'] = Date("m/d/Y", $toDate);
					}

					$dataPerformance	= array();
					$date		= array(
						'fromDate'	=> $fromDate,
						'toDate'	=> $toDate
					);
					list($range, $default) = $this->createDateRangeArray(Date('Y-m-d', $fromDate), Date('Y-m-d', $toDate));
					$dataTraffic = YouNet_Model_DbTable_Visitors::getVisitorViewPartitionStatistic($this->_contest->id, $id_pages, $date);
					$dataTraffic[] = YouNet_Model_DbTable_Likes::getLikeStatistic($this->_contest->id, $id_pages, $date);
					foreach ($list as $e)
					{
						if ($e === YouNet_Model_DbTable_Visitors::STATISTIC_KEY)
							$dataPerformance[] = array_merge($dataTraffic[0], array('showInLegend' => false));
						else if ($e === YouNet_Model_DbTable_Likes::STATISTIC_KEY)
							$dataPerformance[] = array_merge($dataTraffic[3], array('showInLegend' => false));
						else if ($e === Core_Model_DbTable_Votes::STATISTIC_KEY)
						{
							$statistic = Core_Model_DbTable_Votes::getVoteStatistic($this->_contest->id, $date);
							$dataPerformance[] = $voteSeries = array_merge($statistic, array('showInLegend' => false));
						}
					}
					if (!isset($voteSeries))
						$voteSeries = Core_Model_DbTable_Votes::getVoteStatistic($this->_contest->id, $date);
					/**/
					list($rangeAgeGender, $dataAgeGender) = $this->getDataGenderAge($ageGenderList, $date);
					/**/

					$activityForm->populate($params);
					$demographicForm->populate($params);
				}
			}
			else
			{
				$params = $this->_getAllParams();
				$params['options'] = $list =  array(YouNet_Model_DbTable_Visitors::STATISTIC_KEY, YouNet_Model_DbTable_Likes::STATISTIC_KEY, Core_Model_DbTable_Votes::STATISTIC_KEY);
				$params['dlist'] = 'view';
				$params['tlist'] = 'view,like,vote';


				$timeStart = $this->_contest->_getTimeStart();
				if ($timeStart > time())
					$fromDate = Core_Util::getTimeAt0($this->_contest->time_created);
				else
					$fromDate = Core_Util::getTimeAt0($this->_contest->_getTimeStart());
				$params['fromDate'] = Date("m/d/Y", $fromDate);

				$timeEnd = $this->_contest->_getTimeEnd();
				if ($timeEnd > time())
					$toDate = Core_Util::getTimeAt0(time());
				else
					$toDate = Core_Util::getTimeAt0($this->_contest->_getTimeEnd());
				$params['toDate'] = Date("m/d/Y", $toDate);

				$dataPerformance	= array();
				$date		= array(
					'fromDate'	=> $fromDate,
					'toDate'	=> $toDate
				);

				list($range, $default) = $this->createDateRangeArray(Date('Y-m-d', $fromDate), Date('Y-m-d', $toDate));
				$dataTraffic = YouNet_Model_DbTable_Visitors::getVisitorViewPartitionStatistic($this->_contest->id, $id_pages, $date);
				$dataTraffic[] = YouNet_Model_DbTable_Likes::getLikeStatistic($this->_contest->id, $id_pages, $date);
				foreach ($list as $e)
				{
					if ($e === YouNet_Model_DbTable_Visitors::STATISTIC_KEY)
						$dataPerformance[] = array_merge($dataTraffic[0], array('showInLegend' => false));
					else if ($e === YouNet_Model_DbTable_Likes::STATISTIC_KEY)
						$dataPerformance[] = array_merge($dataTraffic[3], array('showInLegend' => false));
					else
					{
						$statistic = Core_Model_DbTable_Votes::getVoteStatistic($this->_contest->id, $date);
						$dataPerformance[] = $voteSeries = array_merge($statistic, array('showInLegend' => false));
					}
				}
				if (!isset($voteSeries))
					$voteSeries = Core_Model_DbTable_Votes::getVoteStatistic($this->_contest->id, $date);
				/**/
				list($rangeAgeGender, $dataAgeGender) = $this->getDataGenderAge($ageGenderList, $date);
				/**/
				$activityForm->populate($params);
				$demographicForm->populate($params);
				$form->populate($params);
			}	
			
			//If valid date we process label information and enable after buffer function
			if (isset($fromDate))
			{
				$newMultiOptions = array();
				foreach ($dataTraffic as $id => $series)
				{
					$series['name'] = $series['name'] . array_sum($series['data']);
					if (in_array($series['younet_id_key'], array(YouNet_Model_DbTable_Visitors::STATISTIC_KEY, YouNet_Model_DbTable_Likes::STATISTIC_KEY)))
						$newMultiOptions[$series['younet_id_key']] = $series['name'];
					$dataTraffic[$id] = $series;
				}
				$newMultiOptions[Core_Model_DbTable_Votes::STATISTIC_KEY] = Core_Model_DbTable_Votes::TOTAL_VOTER_NAME . (isset($voteSeries) ? array_sum($voteSeries['data']) : 0);
				$activityForm->options->setMultiOptions($newMultiOptions);

				register_shutdown_function(array($this, 'prepareDataAfterExit'), $ageGenderList, array(
					'fromDate'	=> $fromDate,
					'toDate'	=> $toDate
				));
			}
			
			$this->view->activtyForm = $activityForm;
			$this->view->demographicForm = $demographicForm;
			$this->view->dataTraffic = $dataTraffic;
			$this->view->form		= $form;
			$this->view->range		= $range;
			$this->view->fromDate	= isset($fromDate) ? Date('M d, Y', $fromDate) : 'N/A';
			$this->view->toDate		= isset($toDate) ? Date('M d, Y', $toDate) : 'N/A';
			$this->view->dataPerformance	= $dataPerformance;
            $rangeAgeGender[]           = 'Unknown';
			$this->view->rangeAgeGender = $rangeAgeGender;
			$this->view->dataAgeGender = $dataAgeGender;
		}
		$this->view->contest = $this->_contest;
	}
	public function prepareDataAfterExit($ageGenderList, $params)
	{
		if (isset($params['fromDate']))
		{
			 $notProcess = array_diff(array('view','like','vote'),array($ageGenderList));
			 foreach ($notProcess as $e)
			 {
				  $this->getDataGenderAge($e, $params);
			 }
		}	
	}
	public function getDataGenderAge($name, $param)
	{
		$id_pages   = Core_Model_DbTable_Pages::getInstance()->getArrayPagesID($this->_contest->id);
		switch ($name) {
			case 'view':
				$data = YouNet_Model_DbTable_Visitors::getVisitorDetailStatistic($this->_contest->id, $id_pages, $param);
				return $data;
				break;
			case 'vote':
				$data = Core_Model_DbTable_Votes::getVoteDetailStatistic($this->_contest->id, $param);
				return $data;
				break;
			case 'like':
				$data = YouNet_Model_DbTable_Likes::getLikeDetailStatistic($this->_contest->id, $id_pages, $param);
				return $data;
				break;
			default:
				break;
		}
	}

	public function preproccessData($range, $statistic, $name, $color)
	{
		$yDateViews = array();
		foreach ($statistic as $v)
		{
			$yDateViews[$v['date']] = intval($v['number'], 10) ;
		}
		$yDateViews = array_merge($range, $yDateViews); 
		$data = array();
		foreach ($yDateViews as $id => $val)
			$data[] = $val;
		
		return array(
			'name'	=> $name,
			'color' => $color,
			'data'	=> $data
		);
	}
	
	public function createDateRangeArray($strDateFrom,$strDateTo)
	{
		// takes two dates formatted as YYYY-MM-DD and creates an
		// inclusive array of the dates between the from and to dates.

		// could test validity of dates here but I'm already doing
		// that in the main script

		$aryRange=array();
		$arrRangeDefault = array();
		
		$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
		$iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));

		if ($iDateTo>=$iDateFrom)
		{
			array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
			$arrRangeDefault[date('Y-m-d',$iDateFrom)] = 0;
			while ($iDateFrom<$iDateTo)
			{
				$iDateFrom+=86400; // add 24 hours
				array_push($aryRange, date('Y-m-d',$iDateFrom));
				$arrRangeDefault[date('Y-m-d',$iDateFrom)] = 0;
			}
		}
		return array($aryRange, $arrRangeDefault);
	}
	public function exportEntriesAction()
	{
		$this->disableAutoRender();
		$filename       = sprintf('entries-list-report-%d-%s-GMT-0.xls',$this->_contest->id,date('F j, Y, g:i a'));
		$this->_doExportEntries($filename);
	}
	
	public function exportParticipantsAction()
	{
		$this->disableAutoRender();
		$filename       = sprintf('participants-list-report-%d-%s-GMT-0.xls',$this->_contest->id,date('F j, Y, g:i a'));
		$this->_doExportParticipants($filename);
	}
	
	public function exportVotersAction()
	{
		$this->disableAutoRender();
		$filename       = sprintf('voters-list-report-%d-%s-GMT-0.xls',$this->_contest->id,date('F j, Y, g:i a'));
		$this->_doExportVoters($filename);
	}
	
	public function exportRegistrantsAction()
	{
		$this->disableAutoRender();
		$filename       = sprintf('registrants-list-report-%d-%s-GMT-0.xls',$this->_contest->id,date('F j, Y, g:i a'));
		$this->_doExportRegistrants($filename);
	}
	
	protected function _sendToBrowser($phpExcel, $filename)
	{
        $phpExcel->setActiveSheetIndex(0);
        //Output the generated excel file so that the user can save or open the file.
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        header("Cache-Control: max-age=0");

        $objWriter = PHPExcel_IOFactory::createWriter($phpExcel, "Excel5");
        $objWriter->save("php://output");
        exit;
	}
	
	protected function _doExportEntries($filename)
	{
        require_once("PHPExcel/PHPExcel.php"); 
        $phpExcel = new PHPExcel();
                   
        $active_sheet = $phpExcel->getActiveSheet();
        
		$this->_contest->exportEntries($active_sheet);
        
        $this->_sendToBrowser($phpExcel, $filename);
	}
	
	protected function _doExportParticipants($filename)
	{
        require_once("PHPExcel/PHPExcel.php"); 
        $phpExcel = new PHPExcel();
                   
        $active_sheet = $phpExcel->getActiveSheet();
        
		$this->_contest->exportParticipants($active_sheet);
        
        $this->_sendToBrowser($phpExcel, $filename);
	}
	
	protected function _doExportVoters($filename)
	{
        require_once("PHPExcel/PHPExcel.php"); 
        $phpExcel = new PHPExcel();
                   
        $active_sheet = $phpExcel->getActiveSheet();
        
		$this->_contest->exportVoters($active_sheet);
        
        $this->_sendToBrowser($phpExcel, $filename);
	}
	
	protected function _doExportRegistrants($filename)
	{
        require_once("PHPExcel/PHPExcel.php"); 
        $phpExcel = new PHPExcel();
                   
        $active_sheet = $phpExcel->getActiveSheet();
        
		$this->_contest->exportRegistrants($active_sheet);
        
        $this->_sendToBrowser($phpExcel, $filename);
	}

}
